document.addEventListener('DOMContentLoaded', function() {
  const imageInput = document.getElementById('imageInput');
  const splitButton = document.getElementById('splitButton');

  splitButton.addEventListener('click', function() {
    const file = imageInput.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function(e) {
        const img = new Image();
        img.onload = function() {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          const width = img.width / 2;
          const height = img.height / 2;

          for (let i = 0; i < 2; i++) {
            for (let j = 0; j < 2; j++) {
              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img, i * width, j * height, width, height, 0, 0, width, height);
              
              canvas.toBlob(function(blob) {
                chrome.runtime.sendMessage({
                  action: 'downloadImage',
                  imageData: blob,
                  fileName: `split_image_${i}_${j}.png`
                });
              }, 'image/png');
            }
          }
        };
        img.src = e.target.result;
      };
      reader.readAsDataURL(file);
    } else {
      alert('请先选择一张图片');
    }
  });
});